//
//  ProductExchangController.m
//  cooba-iOS
//
//  Created by 郭四虎 on 16/4/25.
//  Copyright © 2016年 YouKu. All rights reserved.
//

#import "ProductExchangController.h"
#import "AddressModel.h"
#import "EditAddressController.h"
#import "ForgetPasswordControllerViewController.h"

@interface ProductExchangController ()<UIScrollViewDelegate>
{
    UILabel *successLb;
    UILabel *msgLb;
}
@property (strong, nonatomic) AddressModel *address;
@property (weak, nonatomic) IBOutlet UIImageView *ima;

@property (weak, nonatomic) IBOutlet UIScrollView *scroll;
@property (weak, nonatomic) IBOutlet UIButton *addreBtn;

@property (weak, nonatomic) IBOutlet UILabel *pro_name;
@property (weak, nonatomic) IBOutlet UILabel *pro_number;
@property (weak, nonatomic) IBOutlet UILabel *pro_left;

@property (weak, nonatomic) IBOutlet UILabel *act_reward;
@property (weak, nonatomic) IBOutlet UILabel *act_time;
@property (weak, nonatomic) IBOutlet UILabel *act_condition;

@property (weak, nonatomic) IBOutlet UILabel *addressLb;
@property (weak, nonatomic) IBOutlet UITextView *remark;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *botton;

@property(strong, nonatomic)UIView *notiView;

@end

@implementation ProductExchangController
- (void)injected{
    [self viewDidLoad];
}

- (UIView *)notiView
{
    if (!_notiView) {
        _notiView = [[UIView alloc]initWithFrame:SCREEN];
        _notiView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
        
        UIView *messageView = [[UIView alloc]initWithFrame:CGRectMake(50, HEIGHT/2-165/2, WIDTH - 100, 165)];
        messageView.backgroundColor = [UIColor whiteColor];
        messageView.layer.cornerRadius = 5;
        [_notiView addSubview:messageView];
        
        UILabel *tit = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, messageView.width, 30)];
        tit.text = @"温馨提示";
        font(tit, 19);
        tit.textAlignment = NSTextAlignmentCenter;
        [messageView addSubview:tit];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10, tit.bottom +5, messageView.width- 20, 1)];
        line.backgroundColor = [UIColor lightGrayColor];
        [messageView addSubview:line];
        
        successLb = [[UILabel alloc]initWithFrame:CGRectMake(0, line.bottom+5, messageView.width, 30)];
        successLb.textAlignment = NSTextAlignmentCenter;
        font(successLb, 16);
        successLb.textColor = [UIColor lightGrayColor];

        [messageView addSubview:successLb];
        
        msgLb = [[UILabel alloc]initWithFrame:CGRectMake(0, successLb.bottom +5, messageView.width, 30)];
        msgLb.textAlignment = NSTextAlignmentCenter;
        msgLb.textColor = [UIColor lightGrayColor];
        font(msgLb, 15);
       
        [messageView addSubview:msgLb];
        
        UIButton *confirm = [UIButton buttonWithType:UIButtonTypeCustom];
        confirm.frame = CGRectMake(messageView.width/2-40, msgLb.bottom +10, 80, 30);
        confirm.backgroundColor = RGBcolor(43, 170, 250);
        confirm.layer.cornerRadius = 5;
        [confirm setTitle:@"确定" forState:UIControlStateNormal];
        [confirm addTarget:self action:@selector(dismissNoti) forControlEvents:UIControlEventTouchUpInside];
        [messageView addSubview:confirm];
    }
    return _notiView;
}

- (void)dismissNoti
{
    [self.notiView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initUI];
    [self checkAddress];
}

- (void) keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
//    CGFloat offset = kbHeight - (HEIGHT - _suggestionLv.frame.origin.y - _suggestionLv.frame.size.height) + 80;
//    
//    NSLog(@"%F %F %F",kbHeight,_suggestionLv.frame.origin.y,_suggestionLv.frame.size.height);
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(kbHeight > 0) {
        [UIView animateWithDuration:duration animations:^{
            _botton.constant = kbHeight;
            [self.scroll setContentOffset:CGPointMake(WIDTH, 690*SCALEX)];
        }];
    }
}

///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        _botton.constant = 0;
    }];
}

- (void)initUI
{
    NSString *url = [NSString stringWithFormat:@"%@?url=%@",GETICON,_model.icon];
    [self.ima sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"image1.png"]];
    
    _pro_name.text = _model.name;
    
    NSString *pstr = [NSString stringWithFormat:@"%@ 剩余", _model.num];
    NSMutableAttributedString *nstr = [[NSMutableAttributedString alloc]initWithString:pstr];
    [nstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, _model.num.length)];
    _pro_number.attributedText = nstr;
    
    NSString *qstr = [NSString stringWithFormat:@"%@ 积分", _model.integral_num];
    NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:qstr];
    [mstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, _model.integral_num.length)];
    _pro_left.attributedText = mstr;
    
    _act_reward.text = [NSString stringWithFormat:@"兑换规则：%@",_model.ex_type];
    _act_time.text = [NSString stringWithFormat:@"活动时间：%@ 至 %@",[self formaterYMH:_model.public_date],[self formaterYMH: _model.valid_date]];
    
    _addressLb.layer.borderColor = [UIColor redColor].CGColor;
    _addressLb.layer.borderWidth = 2;
    
    _remark.layer.borderWidth = 1;
    _remark.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
}

- (NSString *)formaterYMH:(NSString *)date
{
    NSDateFormatter *formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dat = [formater dateFromString:date];
    [formater setDateFormat:@"yyyy-MM-dd"];
    NSString *datestr = [formater stringFromDate:dat];
    return datestr;
}
- (void)checkAddress
{
    if (![Myuser sharedUser].login_id) {
        return;
    }
    [MyAFN POST:CHECKADDRESS parameters:@{@"login_id":[Myuser sharedUser].login_id} block:^(id responseObject) {
        
        if ([[responseObject objectForKey:@"status"]integerValue]) {
            if ([responseObject objectForKey:@"id"]) {
                [_addreBtn setTitle:@"修改地址" forState:UIControlStateNormal];
                
                _address = [[AddressModel alloc]init];
                [_address setValuesForKeysWithDictionary:responseObject];
                
                NSArray *arr = [_address.address componentsSeparatedByString:@"@@"];
                NSString *str;
                if (arr.count == 2) {
                    str = [NSString stringWithFormat:@"%@%@",arr[0],arr[1]];
                }else{
                    str = arr[0];
                }
                
                NSString *qstr = [NSString stringWithFormat:@" 寄送至：%@", str];
                NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:qstr];
                [mstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 5)];
                _addressLb.attributedText = mstr;
                
            }else{
                
                
            }
        }
        
    } error:^(NSError *error) {
        
    } fromController:self];
}
- (IBAction)updataAddress:(id)sender {
    
    if (![Myuser sharedUser].login_id) {
        Message(@"请登录");
        return;
    }
    
    EditAddressController *controller = [[EditAddressController alloc]init];
    controller.model = _address;
    controller.changeAddress = ^(AddressModel *model){
        
        [_addreBtn setTitle:@"修改地址" forState:UIControlStateNormal];
        
        self.address = model;
        
        NSArray *arr = [_address.address componentsSeparatedByString:@"@@"];
        NSString *str;
        if (arr.count == 2) {
            str = [NSString stringWithFormat:@"%@%@",arr[0],arr[1]];
        }else{
            str = arr[0];
        }
        
        NSString *qstr = [NSString stringWithFormat:@" 寄送至：%@", str];
        NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:qstr];
        [mstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 5)];
        _addressLb.attributedText = mstr;
    };
    [self.navigationController pushViewController:controller animated:YES];
}

- (BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

- (BOOL)valiMobile:(NSString *)mobilePhone {
    //验证手机号
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobilePhone];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobilePhone];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobilePhone];
    
    if (isMatch1 || isMatch2 || isMatch3){
        return YES;
    }
    return NO;
}


- (IBAction)confirmExchange:(id)sender {
    
    if (![Myuser sharedUser].login_id) {
        Message(@"请登录");
        return;
    }
    
    if (!_address) {
        Message(@"请填写收货地址");
        return;
    }
    
    if(![self valiMobile:[Myuser sharedUser].login_id]){
    
        [Myuser alertWithTitle:@"提示" Msg:@"还未绑定手机，前去绑定手机？" target:self action:^{
            ForgetPasswordControllerViewController *fc = [[ForgetPasswordControllerViewController alloc]init];
            
            fc.isBinding = YES;
            fc.uuid = USERID;
            
            [self.navigationController pushViewController:fc animated:YES];
        }];
        return;
    }
    NSDictionary *parameter;
    if ([_model.type isEqualToString:@"2"]) {
        
        if (factory) {
            if (![factory isEqualToString:@"TBS"]) {
                Message(@"本车暂无流量可兑换");
                return;
            }
        }else{
            Message(@"请先连接车载WiFi");
            return;
        }
        
        parameter = @{@"product_id":_model.productid,@"login_id":[Myuser sharedUser].login_id,@"ex_info_id":_address.addressid,@"remark":_remark.text,@"mac":USERMAC};
    }else{
        parameter = @{@"product_id":_model.productid,@"login_id":[Myuser sharedUser].login_id,@"ex_info_id":_address.addressid,@"remark":_remark.text};
    }
    
    [MyAFN POST:EXPRODUCT parameters:parameter block:^(id responseObject) {
        
        if ([[responseObject objectForKey:@"status"]integerValue]) {
            
            [self.view addSubview:self.notiView];
            
            if ([responseObject objectForKey:@"ex_status"]) {
                successLb.text = @"兑换失败";
                msgLb.text = [responseObject objectForKey:@"msg"];
            }else{
                successLb.text = @"恭喜，兑换成功";
                msgLb.text = [NSString stringWithFormat:@"剩余 %@ 积分",[responseObject objectForKey:@"integralTotal"]];
                [Myuser sharedUser].allTotalIntegral =[responseObject objectForKey:@"integralTotal"];
                [[NSNotificationCenter defaultCenter]postNotificationName:@"leftNum" object:nil];
                self.changeNum();
            }
            
        }else{
            
            [self.view performSelector:@selector(Message:) withObject:@"兑换失败，请重试" afterDelay:0.5];
        }
        
    } error:^(NSError *error) {
        
    } fromController:self];
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.scroll.contentSize = CGSizeMake(WIDTH, 690*SCALEX);
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
